package com.xxd.rpt2.config

import com.xxd.rpt2.Entity.Role
import com.xxd.rpt2.Entity.User
import com.xxd.rpt2.service.UserService
import org.apache.shiro.authc.AuthenticationException
import org.apache.shiro.authc.AuthenticationInfo
import org.apache.shiro.authc.AuthenticationToken
import org.apache.shiro.authc.SimpleAuthenticationInfo
import org.apache.shiro.authc.UsernamePasswordToken
import org.apache.shiro.authz.AuthorizationInfo
import org.apache.shiro.authz.SimpleAuthorizationInfo
import org.apache.shiro.realm.AuthorizingRealm
import org.apache.shiro.subject.PrincipalCollection
import org.apache.shiro.util.ByteSource
import org.springframework.beans.factory.annotation.Autowired

class BaseRealm extends AuthorizingRealm {

    @Autowired
    UserService userService

    /**
     * 授权
     * @param principals
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        User user = (User) principals.getPrimaryPrincipal();
        //角色授权可有可无
        for (Role role : user.getRoleList()) {
            authorizationInfo.addRole(role.getCode());
        }
        return authorizationInfo;
    }

    /**
     * 验证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken usernamePasswordToken = (UsernamePasswordToken)token
        //println(usernamePasswordToken.getPassword())
        String username = usernamePasswordToken.getUsername()
        User user = userService.findByName(username)
        if(user){
            AuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(user,user.getPassword(),
                    ByteSource.Util.bytes(user.getCredentialsSalt()),getName())
            return simpleAuthenticationInfo
        }
        return null
    }
}
